import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;
import sun.plugin2.message.Message;

import java.util.Properties;

public class until {
    /**
     * @param host    服务器地址 smtp.163.com
     * @param from    发送人
     * @param pwd     发送人授权码
     * @param to      接受人
     * @param sub     标题
     * @param content 正文
     */
    public static void sendEmail(String host, String from, String pwd, String to, String sub, int content) {
        Properties props = new Properties();
        props.put("mail.smtp.host", host);// 设置服务器
        props.put("mail.smtp.auth", "true");// 身份验证
        Session session = Session.getDefaultInstance(props, null);
        // 设置true可以在控制台上看到发送邮件的过程
        session.setDebug(false);
        // 用session对象来创建并初始化邮件对象
        MimeMessage mimeMsg = new MimeMessage(session);

        // 设置发送人
        try {
            mimeMsg.setFrom(new InternetAddress(from));
            mimeMsg.setSubject(sub);// 设置邮件标题
            mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
        } catch (Exception e) {
            e.printStackTrace();
        }

        try {
            MimeMultipart mp = new MimeMultipart();
            BodyPart body = new MimeBodyPart();
            body.setText(String.valueOf(content));
            mp.addBodyPart(body);
            mimeMsg.setContent(mp);
            mimeMsg.saveChanges();
            Transport transport = session.getTransport("smtp");
            // 链接邮件服务器并进行身份验证
            transport.connect(host, from, pwd);
            // 发送邮件
            transport.sendMessage(mimeMsg, mimeMsg.getRecipients(Message.RecipientType.TO));
            // 发送邮件成功
            transport.close();
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }
}
